<template>
  <el-dialog
    :title="title"
    :visible.sync="editVisible"
    width="500px"
  >
    <el-form label-position="top" @submit.native.prevent>
      <el-form-item :label="`${$t('product.productType.type.productMenu')}：`" >
        <el-input v-model="directoryName" @keyup.enter.native.prevent="submit" :placeholder="$t('product.productType.placeholder.productMenuInput')"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="editVisible = false">{{ $t('common.base.cancel') }}</el-button>
      <el-button type="primary" @click="submit" :loading='loading'>{{ $t('common.base.makeSure') }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  setTreeList,
  updateTree
} from '@src/api/ProductV2Api';

export default {
  name:'edit-directory-dialog',
  data(){
    return{
      editVisible:false,
      directoryName:'',
      propsData:{},
      loading:false
    }
  },
  computed:{
    title(){
      if(this.propsData.type==='createTop') return this.$t('product.productType.title.title1')
      else if(this.propsData.type==='edit') return this.$t('product.productType.title.title2')
      else return this.$t('product.productType.title.title3')
    }
  },
  methods:{
    open(propsData){
      this.directoryName=propsData.name;
      this.propsData=propsData;
      this.editVisible=true;
    },
    async submit(){
      if(this.directoryName.length>100){
        return this.$notify.error({
          title: this.$t('common.base.error'),
          message: this.$t('product.productType.tips.tip10', {count: '100'}),
          duration: 2000,
        });
      }
      const index=this.propsData.list.findIndex(item=>item.name===this.directoryName);
      const oldIndex=this.propsData.list.findIndex(item=>item.name===this.propsData.name);
      if(index>-1 && oldIndex!==index) return this.$notify.error({
        title: this.$t('common.base.error'),
        message: this.$t('product.productType.tips.tip11'),
        duration: 2000,
      });
      this.loading=true;
      const type=this.propsData.type;
      let params,api;
      if(type==='edit'){
        api=updateTree;
        params={
          id:this.propsData.id,
          catalogName:this.directoryName
        }
      }else{
        api=setTreeList;
        params={
          parentId:this.propsData.id,
          catalogName:this.directoryName
        }
      }
      let {code,message,result}=await api(params);
      if(code===0){
        this.$notify.success({
          message,
          duration: 2000,
        });
        this.editVisible=false;
        this.$emit('success',result.parentIds);
      }else{
        this.$notify.error({
          title: this.$t('common.base.requestError'),
          message,
          duration: 2000,
        });
      }
      this.loading=false;
    }
  }
}
</script>